<?php
/**
 * house service
 */
namespace App\Service;

use App\Models\EwHouseReco;
use App\Models\EwHouse;
use App\Models\EwHouseSeco;
use App\Models\EwHouseRent;
use App\Service\CatsService;
use App\Util\Fun;

class HouseRecoService  extends BaseService
{
	const DISPLAY_TRUE = 1;		//显示标识：是
	const DISPLAY_FALSE = 0;	//显示标识：否
	const DEL_TRUE = 1;			//删除标识：是
	const DEL_FALSE = 0;		//删除标识：否

	public static function getHouseList($params)
	{
		$params->city_id = property_exists($params,'city_id') ? $params->city_id : 63;
		
		// $sql = 'SELECT 
		// h.list_id AS id,h.list_id AS go_url,CASE h.house_type WHEN "xinfang" THEN 1 WHEN "ershoufang" THEN 8 ELSE 9 END AS groupId,h.three_url,h.house_type,
		// h.thumb,h.name,h.layout,h.area,h.house_orien,h.house_name,
		// IFNULL(h.house_tags,"") AS house_tags,
		// h.total_price,h.price,h.unit,h.region,h.address,
		// IFNULL(h.rent_type,"") AS rent_type,
		// h.sources,h.visit,h.lon,h.lat,h.is_self,
		// IFNULL((SELECT COUNT(c.id) 
		// FROM ew_member_collect AS c 
		// WHERE c.list_id = h.list_id AND 
		// c.table_id = (CASE h.house_type WHEN "xinfang" THEN 1 WHEN "ershoufang" THEN 8 ELSE 9 END) AND c.member_id = ' . intval($params->member_id) . '),0) 
		// AS is_collect,
		// IFNULL((SELECT p.id AS praise_id 
		// FROM ew_member_praise AS p 
		// WHERE p.praise = 1 AND h.id = p.list_id AND 
		// p.table_id = (CASE h.house_type WHEN "xinfang" THEN 1 WHEN "ershoufang" THEN 8 ELSE 9 END)  AND p.member_id = ' . intval($params->member_id) . ' ),0) 
		// AS is_praise,
		// IFNULL(h.index_by,0) AS index_by,IFNULL(h.reco_by,0) AS reco_by,h.create_time 

		// FROM ew_house_reco AS h
		// WHERE city_id = ' . $params->city_id . '  AND is_display = 1 AND is_del = 0
		// ORDER BY id DESC
		// LIMIT ' . ($params->p-1)*$params->page_num . ',' . $params->page_num;
		$sql = 'SELECT 
		h.list_id AS id,h.list_id AS go_url,CASE h.house_type WHEN "xinfang" THEN 1 WHEN "ershoufang" THEN 8 ELSE 9 END AS groupId,h.three_url,h.house_type,
		h.thumb,h.name,h.layout,h.area,h.house_orien,h.house_name,
		IFNULL(h.house_tags,"") AS house_tags,
		h.total_price,h.price,h.unit,h.region,h.address,
		IFNULL(h.rent_type,"") AS rent_type,
		h.sources,h.visit,h.lon,h.lat,h.is_self,
		0 is_collect,0 is_praise,0 AS index_by,0 AS reco_by,h.create_time 

		FROM ew_house_reco AS h
		WHERE h.city_id = ' . $params->city_id . '  AND h.is_display = 1 AND h.is_del = 0
		ORDER BY h.id DESC
		LIMIT ' . ($params->p-1)*$params->page_num . ',' . $params->page_num;

		$data = (new Fun)->db_execute($sql);

		return $data;
	}

	/**
	 * [getList 房源列表 APP端列表]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public static function getList($params, $count = FALSE)
	{
		$table_id = self::getTableId();
		//默认获取类型第一条 二手房
		// $arr = CatsService::getTableCats($table_id);
		// $cate_id = current($arr) ? $arr[0]['id'] : NULL;
		// $params->cate_id = (isset($params->cate_id) && ($params->cate_id)) ? $params->cate_id : $cate_id;

		// if (isset($params->is_reco) && $params->is_reco)//获取最新推荐的房源 类型不做筛选
		// 	$params->cate_id = NULL;

		$member_id = property_exists($params,'member_id') ? $params->member_id : 0;
		$builder = new \Phalcon\Mvc\Model\Query\Builder();
		$builder->columns(
			'h.list_id as id,h.list_id as go_url,CASE h.house_type WHEN "xinfang" THEN 1 WHEN "ershoufang" THEN 8 ELSE 9 END AS groupId,h.three_url,h.house_type,
			h.thumb,h.name,
			h.layout,h.area,h.house_orien,h.house_name,
			IFNULL(h.house_tags,"") AS house_tags,
			h.total_price,h.price,h.unit,
			h.region,h.address,
			IFNULL(h.rent_type,"") AS rent_type,
			h.sources,h.visit,
			h.lon,h.lat,
			h.is_self,
			IFNULL((SELECT count(c.id) FROM App\Models\EwMemberCollect c where c.list_id = h.list_id AND c.table_id = (CASE h.house_type WHEN "xinfang" THEN 1 WHEN "ershoufang" THEN 8 ELSE 9 END) AND c.member_id = ' . $member_id . '),0) AS is_collect,
			IFNULL((SELECT p.id AS praise_id FROM App\Models\EwMemberPraise p WHERE p.praise = 1 AND h.id = p.list_id AND p.table_id = (CASE h.house_type WHEN "xinfang" THEN 1 WHEN "ershoufang" THEN 8 ELSE 9 END)  AND p.member_id = ' . intval($member_id) . ' ),0) AS is_praise,
			IFNULL(h.index_by,0) AS index_by,IFNULL(h.reco_by,0) AS reco_by,h.create_time'
			);

		if ($count)
			$builder->columns('h.id');

		$builder->addFrom("App\Models\EwHouseReco", 'h');
		$builder->andWhere("h.is_del = " . self::DEL_FALSE);

		//is_display
		if (isset($params->is_display))
			$builder->andWhere("h.is_display = ". $params->is_display);

		//target_id 获取相关推荐列表
		if (isset($params->target_id) && $params->target_id){
			$arr = new \stdClass();
			$arr->table_id = self::getTableId();
			$arr->list_id  = $params->target_id;
			$data = RecoService::getRecoList($arr);
			if (count($data) > 0){
				$builder->inWhere('h.id', $data);
			}
		}

		//title 
		if (isset($params->title) && $params->title)
			$builder->andwhere('h.name LIKE "%'.$params->title.'%"');

		//tags 
		if (isset($params->tags) && $params->tags)
			$builder->andWhere("h.tags = ". $params->tags);

		//city_id
		if (isset($params->city_id) && $params->city_id)
			$builder->andWhere("h.city_id = ". $params->city_id);

		//cate_id
		// if (isset($params->cate_id) && $params->cate_id)
		// 	$builder->andWhere("h.cate_id = ". $params->cate_id);

		//count 数量
		if ($count)
			return $builder->getQuery()->execute()->count();

		// $sql = " h.app_level DESC,h.order_by DESC, h.create_time DESC, h.id DESC, h.update_time DESC";
		//框架无法使用case when 
		$sql = " h.index_by DESC, h.order_by DESC, h.create_time DESC, h.id DESC, h.update_time DESC";//默认获取 首页 - house
		if (isset($params->is_reco) && $params->is_reco)//获取推荐 - house
			$sql = " h.reco_by DESC, h.order_by DESC, h.create_time DESC, h.id DESC, h.update_time DESC";
		
		//order_by 排序
		if (isset($params->order_by) && $params->order_by)
			$sql = parent::orderBy($params->order_by, $table = "h");

		$builder->orderBy($sql);

		$builder->limit($params->page_num,($params->p-1)*$params->page_num);
		$result = $builder->getQuery();
		return $result->execute();		
	}

	/**
	 * [getSearch 房源搜索 后台端列表]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public static function getSearch($params, $count = FALSE)
	{
		$builder = new \Phalcon\Mvc\Model\Query\Builder();
		$builder->columns(
			'id,h.list_id as go_url,CASE h.house_type WHEN "xinfang" THEN "新房" WHEN "ershoufang" THEN "二手房" ELSE "租房" END AS house_type,h.three_url,
			h.thumb,h.name,
			h.layout,h.area,h.house_orien,h.house_name,
			h.total_price,h.price,
			h.region,h.address,  
			h.sources,h.visit'
			);

		if ($count)
			$builder->columns('h.id');

		$builder->addFrom("App\Models\EwHouseReco", 'h');
		$builder->andWhere("h.is_del = " . self::DEL_FALSE);

		//is_display
		if (isset($params->is_display))
			$builder->andWhere("h.is_display = ". $params->is_display);

		//city_id
		if (isset($params->city_id) && $params->city_id)
			$builder->andWhere("h.city_id = ". $params->city_id);

		// if (isset($params->cate_id) && $params->cate_id)
		// 	$builder->andWhere("h.cate_id = ". $params->cate_id);

		//name 名称
		if (isset($params->name) && $params->name)
			$builder->andwhere('h.name LIKE "%'.$params->name.'%"');

		//region 区域
		if (isset($params->region) && $params->region)
			$builder->andwhere('h.region LIKE "%'.$params->region.'%"');

		//min_price 价格
		if (isset($params->min_price) && $params->min_price)
			$builder->andwhere('h.price > ' . $params->min_price);

		//max_price 价格
		if (isset($params->max_price) && $params->max_price)
			$builder->andwhere('h.price < ' . $params->max_price);

		//layout 户型
		if (isset($params->layout) && $params->layout)
			$builder->andwhere('h.layout LIKE "%'.$params->layout.'%"');

		//address 地址
		if (isset($params->address) && $params->address)
			$builder->andwhere('h.address LIKE "%'.$params->address.'%"');

		//sources 来源
		if (isset($params->sources) && $params->sources)
			$builder->andwhere('h.sources LIKE "%'.$params->sources.'%"');

		//count 数量
		if ($count)
			return $builder->getQuery()->execute()->count();

		$sql = " h.order_by DESC, h.create_time DESC, h.id DESC, h.update_time DESC";
		//order_by 排序
		if (isset($params->order_by))
			$sql = parent::orderBy($params->order_by, $table = "h");

		$builder->orderBy($sql);

		$builder->limit($params->page_num,($params->p-1)*$params->page_num);
		$result = $builder->getQuery();
		return $result->execute();	
	}

	/**
	 * [getTableName 获取数据表名称]
	 * @return [type] [description]
	 */
	public static function getTableName()
	{
		$model = new EwHouseReco;
		return $model->getSource();
	}

	/**
	 * [getSchema 获取数据库名称]
	 * @return [type] [description]
	 */
	public static function getSchema()
	{
		$model = new EwHouseReco;
		return $model->getSchema();
	}

	/**
	 * [getTableId 获取数据表Id]
	 * @return [type] [description]
	 */
	public static function getTableId()
	{
		return ConfigsService::getTable(self::getTableName());
	}

	public static function getModel($id = 0)
	{
		return EwHouseReco::findFirst($id);
	}

	/**
	 * [getInfo 通过主键获取房源详情  APP端 点赞量及当前登录用户是否点赞]
	 * @param  integer $id [description]
	 * @return [type]      [description]
	 */
	public static function getInfo($id = 0, $member_id = NULL)
	{	
		$info = EwHouseReco::findFirst($id);
		if (!$info)
			return NULL;
		$info = $info->toArray();

		$data = new \stdClass();
		$data->go_url  = "";
		$data->groupId = self::getTableId();
		$data->praise = (string)0;
		$data->is_praise = (string)-1;

		$arr = new \stdClass();
		$arr->table_id = self::getTableId();
		$arr->list_id  = $id;
		$arr->praise   = NULL;
		//获取点赞量
		$data->praise = (string)MemberPraiseService::sum($arr);
		//获取当前用户是否点赞
		if ($member_id){
			$arr->member_id = $member_id;
			$data->is_praise = (string)MemberPraiseService::juge($arr);
		}
		
		foreach ($info as $key => $value) {
			$data->$key = $value;
		}
		
		return $data;
	}

	/**
	 * [count 获取总量]
	 * @return [type] [description]
	 */
	public static function count()
	{
		return EwHouseReco::count();
	}

	/**
	 * [getStick 置顶]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function getStick($id)
	{
		if (isset($id) && $id)
			$raw = EwHouseReco::findFirst($id);

		if ($raw){
			$max = EwHouseReco::maximum(['column' => 'order_by']);
			$raw->order_by = $max + 1;
			return $raw->save();
		}
		return NULL;
	}
	
	/**
	 * [visit 浏览量 +1]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function visit($id)
	{
		if (isset($id) && $id)
			$data = EwHouseReco::findFirst($id);

		if ($data){
			$data->visit = $data->visit + 1;
			return $data->save();
		}

		return NULL;
	}

	/**
	 * [display 上架]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function display($id)
	{
		if (isset($id) && $id)
			$data = EwHouseReco::findFirst($id);

		if ($data){
			$data->is_display = $data->is_display ? self::DISPLAY_FALSE : self::DISPLAY_TRUE;
			return $data->save();
		}

		return NULL;
	}

	/**
	 * [delete 移除/恢复数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function delete($id)
	{
		if (isset($id) && $id)
			$data = EwHouseReco::findFirst($id);

		if ($data){
			$data->is_del = $data->is_del ? self::DEL_FALSE : self::DEL_TRUE;
			return $data->save();
		}

		return NULL;		
	}

	/**
	 * [delete 彻底删除数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function forever($id)
	{
		if (isset($id) && $id)
			$row = EwHouseReco::findFirst($id);

		if ($row && $row->delete()){
			switch ($row->house_type) {
				case 'xinfang':
					$model = EwHouse::findFirst($row->list_id);
					break;

				case 'ershoufang':
					$model = EwHouseSeco::findFirst($row->list_id);
					break;

				case 'zufang':
					$model = EwHouseRent::findFirst($row->list_id);
					break;

				default:
					return TRUE;
					break;
			}
			$model->is_reco_you = 0;
			$model->save();
			return TRUE;
		}

		return NULL;
	}

	/**
	 * [save 保存]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public static function save($data)
	{
		$row = new EwHouseReco;
		if (isset($data->id) && $data->id)
			$row = EwHouseReco::findFirst($data->id);

		//查询是否已经推荐了当前数据
		if (isset($data->list_id) && $data->house_type)
			$raw = EwHouseReco::findFirst(['conditions'=>'list_id = ' . $data->list_id . ' AND house_type = "' . $data->house_type . '"']);
		if ($raw)
			$row = $raw;

		//置顶
		if (isset($data->is_stick) && $data->is_stick){
			$max = EwHouseReco::maximum(['column' => 'order_by']);
			$data->order_by = $max + 1;
		}

		if($row && $row -> save((array)$data)) 
		 	return TRUE;
		
	}
}